<?php
class Bizprofile_AuthController extends Zend_Controller_Action {
	public function forgotAction()
	{
		$request = $this->getRequest();
		$auth 	 = Zend_Auth::getInstance();
		
		/**
		 * Redirect to dashboard if user has logged in already
		 */
		if ($auth->hasIdentity()) {
			$this->_redirect($this->view->serverUrl());
		}
		if ($request->isPost()) {
			//$username = $request->getPost('username');
			$email 	  = $request->getPost('email');
			
			$conn = Tomato_Db_Connection::factory()->getMasterConnection();
			$userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('core')->getUserDao();
			$userDao->setDbConnection($conn);
			
			$users = $userDao->find(null, null, array('email' => $email));
			if (count($users) == 0) {
				$this->_helper->getHelper('FlashMessenger')
					->addMessage($this->view->translator('auth_forgot_user_not_found'));
				$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_forgot'));
			} else {
				/**
				 * Send the confirmation link to reset password via email 
				 */
				$user = $users[0];
				$username = $user->user_name;

				$password = substr(md5(rand(100000, 999999)), 0, 8);
				$userDao->updatePasswordFor($username, $password);										
				
				$encodedLink = array(
					'forgot_user_name'    => $username,
					'forgot_password'     => $password,
				);
				$encodedLink = base64_encode(urlencode(Zend_Json::encode($encodedLink)));
				$link    	 = $this->view->serverUrl() . $this->view->url(array('encoded_link' => $encodedLink), 'bizprofile_auth_login_forgot');
				
				$subject = $this->view->translator('auth_mail_subject');
				$content = '';
				$content.= $this->view->translator('auth_mail_hi').' ' . $username . ',<br/>';
				$content.= $this->view->translator('auth_mail_title').'<br/>';
				$content.= $this->view->translator('auth_mail_newpas_is') . $password . '<br/>';
				$content.= $this->view->translator('auth_mail_use_link_title').'<br/>';
				$content.= $link.'<br/>';				
				$content.= $this->view->translator('auth_mail_footer');	
				/**
			 	 * Get mail transport instance
			 	 */
				$transport = Mail_Services_Mailer::getMailTransport();
				
				$mail = new Zend_Mail('utf-8');
				$mail->setFrom($template->from_mail, $template->from_name)					
					->addTo($user->email, $user->user_name)
					->setSubject($subject)
					->setBodyHtml($content)
					->send($transport);

				/**
				 * Redirect
				 */
				$this->_helper->getHelper('FlashMessenger')
					->addMessage($this->view->translator('auth_forgot_sent_mail'));
				$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_forgot'));
			}
		}
	}
	public function changepassAction(){
        $request = $this->getRequest();
        $auth    = Zend_Auth::getInstance();
		$conn = Tomato_Db_Connection::factory()->getMasterConnection();
		$userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('bizprofile')->getUserDao();
		$userDao->setDbConnection($conn);
		
        if ($auth->hasIdentity()){
            $user = $auth->getIdentity();
			if($request->isPost()){
				$user_name 			= $user->user_name;
				$old_password 		= $request->getPost('password');
				$new_password 		= $request->getPost('newpassword');
				$confirm_password 	= $request->getPost('confirmpassword');
				$md5_pass 			= md5($old_password);
				$users 				= $userDao->find(null, null, array('username' => $user_name));				
				$error 				= false;
				if(count($users)>0){
					if($user->password != $md5_pass){
						$error = true;
						$this->_helper->getHelper('FlashMessenger')
							->addMessage($this->view->translator('auth_old_password_wrong'));				
						$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_changepass'));						
					}
				}else {
					$error = true;
					$this->_helper->getHelper('FlashMessenger')
						->addMessage($this->view->translator('auth_user_non_exists'));					
					$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_changepass'));						
				}
				if($old_password && $new_password && $confirm_password){
						if($new_password != $confirm_password){
							$error  = true;
							$this->_helper->getHelper('FlashMessenger')
								->addMessage($this->view->translator('auth_new_password_and_confirm_not_the_same'));					
							$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_changepass'));						
						}
				}else{
					$error  = true;
					$this->_helper->getHelper('FlashMessenger')
						->addMessage($this->view->translator('auth_changepass_info_required'));
					$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_changepass'));												
				}	
				
				if(!$error){
					$changepass = $userDao->updatePasswordFor($user_name, $new_password);	
					
					$this->_helper->getHelper('FlashMessenger')
						->addMessage($this->view->translator('auth_changepass_successfull'));	
					
					$link    = $this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login');
					
					$subject = $this->view->translator('auth_mail_subject_changepass');
					$content = '';
					$content.= $this->view->translator('auth_mail_hi').' ' . $user_name . ',<br/>';
					$content.= $this->view->translator('auth_mail_changepass_title').'<br/>';
					$content.= $this->view->translator('auth_mail_newpas_is') . $new_password . '<br/>';
					$content.= $this->view->translator('auth_mail_changepass_login_link').'<br/>';
					$content.= $link.'<br/>';				
					$content.= $this->view->translator('auth_mail_footer');	
					/**
					 * Get mail transport instance
					 */
					$transport = Mail_Services_Mailer::getMailTransport();
					
					$mail = new Zend_Mail('utf-8');
					$mail->setFrom($template->from_mail, $template->from_name)					
						->addTo($user->email, $user->user_name)
						->setSubject($subject)
						->setBodyHtml($content)
						->send($transport);
						
					$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_changepass'));						
				}
				
			}
		}else{
			$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
		}			
	}
    public function loginAction() {
        $request = $this->getRequest();
        $auth    = Zend_Auth::getInstance();

        /**
        * Redirect to dashboard if user has logged in already
        */
        if ($auth->hasIdentity()){
            $user = $auth->getIdentity();
            if(isset($user->enterprise->id) && $user->enterprise->id){
				$arrRoutes = array(
					'enterprise_id'			=> $user->enterprise->id,
					'enterprise_name'		=> Tomato_Utility_String::removeSign($user->enterprise->company_name_en, '-', true),
				);
                $this->_redirect($this->view->serverUrl().$this->view->url($arrRoutes, 'bizprofile_enterprise_index'));
            }else{
                $this->_redirect($this->view->baseUrl());
            }
        }

        /**
        * Login attemp, show captcha
        */
        $captcha_session = new Zend_Session_Namespace('captcha');
        if ($captcha_session->tries >= 3)
        {
            $captcha = new Zend_Captcha_Image();
            $captcha->setTimeout('300')
            ->setWordLen('6')
            ->setHeight('60')
            ->setWidth('150')
            ->setFont('images/captcha/fonts/ARIAL.TTF')
            ->setImgDir('images/captcha');
            $captcha->generate();
            $this->view->assign('captchaId', $captcha->getId());
        }	
			
		if ($request->isGet()) {
			$invalidLink  = 0; // danh dau chua co encoded_link
			$encoded_link   = $request->getParam('encoded_link',null);
			if($encoded_link){
				$invalidLink = 1;
				// has encoded_link
				$encodedLink = Zend_Json::decode(urldecode(base64_decode($encoded_link)));	
				if (is_array($encodedLink) && isset($encodedLink['forgot_user_name']) && isset($encodedLink['forgot_password'])) {					
					$forgot_user_name = $encodedLink['forgot_user_name'];
					$forgot_password  = $encodedLink['forgot_password'];
					$conn = Tomato_Db_Connection::factory()->getMasterConnection();
					$userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('core')->getUserDao();
					$userDao->setDbConnection($conn);					
					$users = $userDao->find(null, null, array('username' => $forgot_user_name));
					if (count($users) > 0) {
						$invalidLink = 2;					
						$this->view->assign('encodedLink',$encodedLink);
					}
				}
			}
			$this->view->assign('invalidLink',$invalidLink);	
			if($invalidLink==1){
                $this->_helper->getHelper ( 'FlashMessenger' )->addMessage ( $this->view->translator ( 'auth_reset_invalid_link' ) );
			}
		}elseif ($request->isPost()) {
			$forward_changepass = $request->getPost('forward_changepass',null);			
            /**
            * Check captcha
            */
            if ($request->getPost('captcha') != null && !$this->validateCaptcha($request->getPost('captcha'))) {
                $this->_helper->getHelper ( 'FlashMessenger' )->addMessage ( $this->view->translator ( 'auth_login_user_invalid_captcha' ) );
                $this->_redirect ( $this->view->serverUrl () . $this->view->url ( array (), 'bizprofile_auth_login' ) );
            }

            $username = $request->getPost('username');
            $password = $request->getPost('password');
            $adapter  = new Bizprofile_Services_Auth($username, $password);
            $result   = $auth->authenticate($adapter);
            switch ($result->getCode()) {
                /**
                * Found user, but the account has not been activated
                */
                case Bizprofile_Services_Auth::NOT_ACTIVE:
                    $this->_helper->getHelper('FlashMessenger')
                        ->addMessage($this->view->translator('auth_login_user_not_activated'));
                    $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
                    break;
				/**
				* Enterprise Inactive
				*/
				case Bizprofile_Services_Auth::ENTERPRISE_INACTIVE:
						$this->_helper->getHelper('FlashMessenger')
							->addMessage($this->view->translator('auth_login_user_is_inactive'));
						$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));																						
				break;

				/**
				* Enterprise Inactive
				*/
				case Bizprofile_Services_Auth::ENTERPRISE_DELETED:
						$this->_helper->getHelper('FlashMessenger')
							->addMessage($this->view->translator('auth_login_user_is_deleted'));
						$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));										
				break;
				
                /**
                * Logged in successfully
                */
                case Bizprofile_Services_Auth::SUCCESS:
					if($forward_changepass==1){
						$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_changepass'));
					}
                    $user = $auth->getIdentity();

					Tomato_Hook_Registry::getInstance()->executeAction('Bizprofile_Auth_Login_LoginSuccess', $user);

					/**
					* Redirect to the previous request if it is not Ajax request
					* @since 2.0.9
					*/
					$session = new Zend_Session_Namespace(Tomato_Controller_Plugin_UrlTracker::SESSION_NS);
					if (isset($session->previous_url) && $session->previous_url != false) {
						$this->_redirect($this->view->serverUrl() . $session->previous_url);
					}
					else {
						if($user->enterprise != null){
							$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_dashboard_index'));
						}
						else{
							$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'core_index_index'));
						}
					}
                    break;

                /**
                * Not found
                */
                case Bizprofile_Services_Auth::FAILURE:
                default:
                    $this->_helper->getHelper('FlashMessenger')
                        ->addMessage($this->view->translator('auth_login_failure'));
                    $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_auth_login'));
                    break;
            }
        }
    }

    /**
    * Logout Action
    *
    */
    public function logoutAction() {
        $this->_helper->getHelper ( 'viewRenderer' )->setNoRender ();
        $this->_helper->getHelper ( 'layout' )->disableLayout ();

        $auth = Zend_Auth::getInstance ();
        if ($auth->hasIdentity ()) {
            $user = $auth->getIdentity ();

            Tomato_Hook_Registry::getInstance ()->executeAction ( 'Bizprofile_Auth_Login_LogoutSuccess', $user );

            /**
            * Clear session
            */
            Zend_Session::destroy ( false, false );

            $auth->clearIdentity ();
        }
        $this->_redirect ($this->view->serverUrl() . $this->view->url(array(), 'bizprofile_dashboard_index'));
    }

    /**
    * Validates captcha response
    *
    * @param string $captcha
    * @return boolean
    */
    private function validateCaptcha($captcha) {
        $captchaId = $captcha ["id"];
        $captchaInput = $captcha ["input"];
        $captchaSession = new Zend_Session_Namespace ( "Zend_Form_Captcha_" . $captchaId );
        $captchaIterator = $captchaSession->getIterator ();
        $captchaWord = $captchaIterator ["word"];
        if ($captchaWord) {
            if ($captchaInput != $captchaWord) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
}